package com.jacen.etl.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacen.etl.entity.EtlDependentEntity;
import com.jacen.etl.entity.EtlEntity;
import com.jacen.etl.services.EtlDependentService;
import com.jacen.etl.services.EtlService;
import com.jacen.etl.services.ServiceProxyFactory;
import com.jacen.etl.util.HttpParamCaster;
import com.jacen.etl.util.ServletUtils;
import com.jacen.etl.util.Utils;

public class EtlDependentManagerAction {

	private EtlDependentService service = ServiceProxyFactory.createProxy(EtlDependentService.class);
	private EtlService etlService = ServiceProxyFactory.createProxy(EtlService.class);
	private static final Logger logger = LoggerFactory.getLogger(EtlDependentManagerAction.class);

	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @throws ServletException IOException
	 */
	public void getPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String entityName = HttpParamCaster.getUTF8Parameter(request, "entityName");
		int entityId = HttpParamCaster.getIntParameter(request, "entityId",0);
		int page = HttpParamCaster.getIntParameter(request, "page", 1);
		int size = HttpParamCaster.getIntParameter(request, "size",Utils.PAGE_SIZE);
		int entitySize = HttpParamCaster.getIntParameter(request, "entitySize",Utils.PAGE_SIZE);
		Map<String, Object> mapParams = new HashMap<String, Object>();
		mapParams.put("entityName", entityName);
		mapParams.put("entityId", entityId);
		try {
			List<EtlDependentEntity> list = service.getPage(mapParams, page, size);
			
			long count = service.getCount(mapParams);
			long totalpage = (count/size) + ((count%size) == 0 ? 0 : 1);
			
			request.setAttribute("entityName", entityName);
			request.setAttribute("entityId", entityId);
			request.setAttribute("list", list);
			request.setAttribute("count", count);
			request.setAttribute("page", page);
			request.setAttribute("size", size);
			request.setAttribute("entitySize", entitySize);
			request.setAttribute("totalpage", totalpage);
		} catch (Exception e) {
			logger.error("获取依赖列表失败", e);
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
			return;
		}
		request.getRequestDispatcher("/jsp/etldep/list.jsp").forward(request, response);
	}
	
		/**
		 * 新增
		 * @param request
		 * @param response
		 * @return
		 * @throws IOException 
		 * @throws ServletException 
		 */
		public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			EtlDependentEntity entity = new EtlDependentEntity();
			EtlEntity etlEntity = new EtlEntity();
			List<EtlEntity> entityList = new ArrayList<EtlEntity>();
			List<EtlDependentEntity> dependentList = new ArrayList<EtlDependentEntity>();
			String entityId = HttpParamCaster.getUTF8Parameter(request, "entityId");
			try {
				if (request.getMethod().equalsIgnoreCase("get")) {
					etlEntity = etlService.getById(Integer.valueOf(entityId));
					dependentList = service.getList(Integer.valueOf(entityId));//已存在的依赖关系
					List<Integer> ids = new ArrayList<Integer>();
					for(int i=0;i < dependentList.size();i++){
						ids.add(dependentList.get(i).getDependentEntityId());
					}
					ids.add(Integer.valueOf(entityId));
					entityList = etlService.getListNotEntityIds(ids.toArray());
					request.setAttribute("entity", etlEntity);
					request.setAttribute("entityList", entityList);
					request.setAttribute("dependentList", dependentList);
					
					request.getRequestDispatcher("/jsp/etldep/insert.jsp").forward(request, response);
					return;
				}
				String dependent = request.getParameter("dependentEntity");
				entity = ServletUtils.getEntity(request, EtlDependentEntity.class);
				entity.setDependentEntityId(Integer.valueOf(dependent.split("-")[0].toString()));
				entity.setDependentName(dependent.split("-")[1].toString());
				service.insert(entity);
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("error", e.getMessage());
				request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
			}
			response.sendRedirect(request.getContextPath()+"/manage/etlDep?act=getPage&entityId="+entityId);
		}
		
		/**
		 * 修改
		 * @param request
		 * @param response
		 * @return
		 * @throws IOException 
		 * @throws ServletException 
		 */
		public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			try {
				String id = HttpParamCaster.getUTF8Parameter(request, "dependentId");
				if(StringUtil.isEmpty(id)) throw new Exception("参数为空");
				EtlDependentEntity entity = service.getById(Integer.valueOf(id));

				if (request.getMethod().equalsIgnoreCase("get")) {
					request.setAttribute("entity", entity);
					request.getRequestDispatcher("/jsp/etldep/update.jsp").forward(request, response);
					return;
				}

				ServletUtils.updateEntity(request, entity);
				service.update(entity);
				response.sendRedirect(request.getContextPath()+"/manage/etlDep?act=getPage&entityId="+entity.getEntityId());
			} catch (Exception e) {
				logger.error("更新操作失败", e);
				request.setAttribute("error", e.getMessage());
				request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
				return;
			}	
			
		}
		
		/**
		 * 删除
		 * @param request
		 * @param response
		 * @return
		 */
		public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			try {
				String entityId = HttpParamCaster.getUTF8Parameter(request, "entityId");
				String entitySize = HttpParamCaster.getUTF8Parameter(request, "entitySize");
				String id = request.getParameter("id");
				EtlDependentEntity entity = service.getEntityByKey("dependent_id", id);
				service.delete(entity);
				response.sendRedirect(request.getContextPath()+"/manage/etlDep?act=getPage&entityId="+Integer.valueOf(entityId)+"&entitySize="+entitySize);
			} catch (Exception e) {
				logger.error("删除操作失败", e);
				request.setAttribute("error", e.getMessage());
				request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
				return;
			}	
			
		}

}
